package com.yunkecn.transactiondemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @Override
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public String getUserName(String userId) {
        String name = jdbcTemplate.query("SELECT User_RealName name FROM crm_t_portaluser WHERE User_Id =?", new Object[]{userId}, new int[]{Types.VARCHAR}, new ResultSetExtractor<String>() {
            @Override
            public String extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs.next()) {
                    return rs.getString("name");
                } else {
                    return null;
                }
            }
        });
        return name;
    }
    
    @Override
    public int updateUserName(String userId, String name) {
        int result = jdbcTemplate.update("UPDATE crm_t_portaluser SET User_RealName = ? WHERE User_Id = ?", name, userId);

//        this.updateAge(userId);
        return result;
    }
    
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 3)
    public void updateAge(String userId) {
        jdbcTemplate.update("UPDATE crm_t_portaluser SET User_Age = ? WHERE User_Id = ?", new Random().nextInt(100), userId);
//        int i = 0;
//        System.out.println(100 / i);
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    @Transactional
    public int updateAgeUseLongTime(String userId) {
        int result = jdbcTemplate.update("UPDATE test SET age = ? WHERE id = ?", new Random().nextInt(100), 1);
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    @Override
    @Transactional
    public int addUserUseLongTime(String userId) {
        int result = jdbcTemplate.update("INSERT INTO test(age) VALUE (?)", new Random().nextInt(100));
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
    
}
